import {
  forwardRef,
  useImperativeHandle,
  useMemo,
  useRef,
  useState,
  useEffect
} from 'react';
import { message } from 'antd';
import { getMessage } from '@inbiz/react';
import { removeCookie, setCookie } from '@inbiz/utils';
import UploadList from './UploadList';
import UploadButton from './UploadButton';
import UploadDrag from './UploadDrag';
import initUploadData from './utils/initUploaderData';
import { IStatus, IUploaderProps } from './interface';
import { GetCurrentUserSpeedLimit, GetInstanceConfig } from './services';
import { InBizUploadCtx } from './context';
import { useApp } from '@inbiz/utils';
import './index.less';
export interface uploadParams {
  folderId: string | number;
  viewMode: string;
  masterFileld?: string;
}

type uploadReturn = {
  type: string;
  tip: string;
};

interface IGalleryRef {
  getfileList: () => void;
  addFiles: (files: any, params: any) => void;
  closeModal: () => void;
  showPanel: () => void;
}

export type UploaderExports = {
  addfiles: (files: File[], params?: uploadParams) => uploadReturn | undefined;
};

const InbizUpload = forwardRef<UploaderExports, IUploaderProps>(
  (props, ref) => {
    const { thumbnail = false, maxNumber = '', viewMode } = props;
    const [speedLimit, setSpeedLimit] = useState({
      DownloadLimit: 0,
      UploadLimit: 0
    });
    const [secondPass, setSecondPass] = useState(false);
    const galleryRef = useRef<IGalleryRef>({
      getfileList: () => { },
      closeModal: () => { },
      showPanel: () => { },
      addFiles: (files: any, params: any) => { },
    });
    const appInfo = useApp();
    const uploaderData = useMemo(() => {
      const uploader = initUploadData(props, appInfo, galleryRef, speedLimit, secondPass);
      props.onProgress && uploader.on('progress', props.onProgress);
      props.onTotalProgress && uploader.on('totalProgress', props.onTotalProgress);
      return uploader
    }, [props.folderId, speedLimit, secondPass]);
    const statusEnum: IStatus = uploaderData.qq.status;
    useImperativeHandle(
      ref,
      () => ({
        addfiles: (files: File[], params?: uploadParams) => {
          if (files?.length === 0) {
            return;
          }
          const fileList = galleryRef?.current.getfileList() as any || [];
          const noUploadList = fileList.filter(file => file?.status != statusEnum.UPLOAD_FAILED && file?.status != statusEnum.UPLOAD_SUCCESSFUL) || [];
          if (noUploadList.length + files.length > 500) {
            message.error(getMessage('inbizUpload.maxfile500'));
            return { type: 'error', tip: getMessage('inbizUpload.maxfile500') };
          }
          if (files?.length > 500) {
            message.error(getMessage('inbizUpload.maxfile500'));
            return { type: 'error', tip: getMessage('inbizUpload.maxfile500') };
          }
          if (
            maxNumber !== '' &&
            maxNumber !== null &&
            files?.length > Number(maxNumber)
          ) {
            message.error(
              `${getMessage(
                'inbizUpload.beforeMaxfile',
              )}${maxNumber}${getMessage('inbizUpload.afterMaxfile')}`,
            );
            return {
              type: 'error',
              tip: `${getMessage(
                'inbizUpload.beforeMaxfile',
              )}${maxNumber}${getMessage('inbizUpload.afterMaxfile')}`,
            };
          }
          galleryRef?.current.addFiles(files, params);
          return;
        },
        getFiles: () => {
          return galleryRef?.current.getfileList();
        },
        closeModal: () => {
          galleryRef?.current.closeModal();
        },
        showPanel: () => {
          galleryRef?.current.showPanel();
        }
      }),
      [uploaderData],
    );

    useEffect(() => {
      // 外发等未登录，无token、无用户信息时不请求
      if (appInfo?.userInfo?.id) {
        GetCurrentUserSpeedLimit(appInfo.userInfo.id).then(res => {
          if (res && res.result == 0) {
            const speed: { DownloadLimit: number, UploadLimit: number } = JSON.parse(res.speedLimit);
            // 下载限速cookie配置
            if (speed.DownloadLimit) {
              setCookie('maxspeed', String(speed.DownloadLimit))
            } else {
              // 下载不限速删除cookie的配置
              removeCookie('maxspeed')
            }
            if (speed.DownloadLimit || speed.UploadLimit) {
              setSpeedLimit(speed)
            }
          }
        });
      }
      GetInstanceConfig().then(res => {
        setSecondPass(res?.config?.SecondPass ?? false);
      })
    }, []);

    return (
      <div
        className={
          thumbnail
            ? 'react-fine-uploader-gallery-files-thumb'
            : 'react-fine-uploader-gallery-files-list'
        }
      >
        <InBizUploadCtx.Provider
          value={{ ...props, uploader: uploaderData, statusEnum }}
        >
          <UploadList ref={galleryRef} viewMode={viewMode} />
        </InBizUploadCtx.Provider>
      </div>
    );
  },
);

InbizUpload.UploadButton = UploadButton;

InbizUpload.UploadDrag = UploadDrag;

InbizUpload.displayName = 'InbizUpload';

export default InbizUpload;
